package edu.gatech.gitmad.catbug.formation;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class HTTPGet {
		private String HTML;
		private URL url;	
		private Thread thread;
		
		public HTTPGet(URL url) {
			this.url = url;
		}
		
		public HTTPGet(String urlString) {
			try {
				url = new URL(urlString);
			}
			catch (MalformedURLException e) {
				e.printStackTrace();
				System.exit(0);
			}
		}
		
		private HttpURLConnection connect() {
			HttpURLConnection conn = null;
			try {
				conn = (HttpURLConnection)url.openConnection();
				conn.setInstanceFollowRedirects(false);
				conn.setRequestMethod("GET");
				//BrowserInfo.cookieJar.giveCookies(conn);
				conn.connect();
				//BrowserInfo.cookieJar.updateFrom(conn);
			}
			catch (IOException e) {
				e.printStackTrace();
				System.exit(0);
			}
			return conn;
		}
		
		public void execute() {
			thread = new Thread(new NetworkOperation());
			thread.start();
		}
		
		public void waitForThis() {
			if (thread != null) {
				try {
					thread.join();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
		
		public String getHTML() {
			waitForThis();
			return HTML;
		}

		private class NetworkOperation implements Runnable {
			public void run() {
				HTML = "";
				HttpURLConnection conn = connect();
				try {
					BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
					String line;
					while ((line = in.readLine()) != null) {
						HTML += line.replace("\t","");
					}
					in.close();
					conn.disconnect();
				}
				catch (IOException e) {
					e.printStackTrace();
					System.exit(0);
				}
				if (thread != null) {
					thread = null;
				}
			}
		}
}
